package com.esd.crm.controller;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TimeZone;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.esd.crm.Constants;
import com.esd.crm.entity.Address;
import com.esd.crm.entity.Customer;
import com.esd.crm.entity.Orders;
import com.esd.crm.service.AddressService;
import com.esd.crm.service.CustomerService;
import com.esd.crm.service.OrdersService;
import com.esd.crm.service.ProductService;

@Controller
@RequestMapping("/security")
public class OrderController {
	private static final Logger logger = LogManager.getLogger(OrderController.class);

	@Autowired
	private OrdersService ordersService;
	@Autowired
	private CustomerService customerService;
	@Autowired
	private AddressService addressService;
	@Autowired
	private ProductService productService;

	private void scyUpdateCustomerTotal(String orderNumber) {

		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderNumber", orderNumber);
		Orders record = ordersService.selectNumberTotalByOrderNumber(param);
		Orders update = ordersService.selectByOrderNumber(param);
		update.setTotal(record.getTotal());
		if (record.getTotal() == null) {
			record.setTotal(new BigDecimal(0));
		}
		update.setPayable(record.getTotal().subtract(update.getPaid()));
		update.setNumber(record.getNumber());
		logger.info(record.toString());
		ordersService.updateByPrimaryKeySelective(update);
	}

	/**
	 * 跳转更新订单页
	 */
	@RequestMapping(value = "/updateOrder", method = RequestMethod.GET)
	public ModelAndView updateOrderGet(HttpSession session, HttpServletRequest request) {
		logger.info("跳转到更新订单页");
		ModelAndView mv = new ModelAndView("order/order_update");
		String orderNumber = request.getParameter("orderNumber");
		if (StringUtils.isNotBlank(orderNumber)) {
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("orderNumber", orderNumber);
			Orders orders = ordersService.selectByOrderNumber(param);
			String address = orders.getAddress();
			if (StringUtils.isNoneBlank(address)) {
				mv.addObject("address", address);
				Address a = addressService.selectByPrimaryKey(Integer.valueOf(address));
				StringBuffer sb = new StringBuffer();
				if (a != null) {
					sb.append(a.getAddress()).append(" ");
					sb.append(a.getDetailedAddress()).append(" ");
					sb.append(a.getName()).append(" ");
					sb.append(a.getTelephone());
					mv.addObject("address", a.getId());
					mv.addObject("addressText", sb.toString());
				}
			}
			mv.addObject("id", orders.getId());
			mv.addObject("remark", orders.getRemark());
			mv.addObject("freightstation", orders.getFreightstation());
			mv.addObject("freightstationcard", orders.getFreightstationcard());
			mv.addObject("paymentStatus", orders.getPaymentstatus());
			
			mv.addObject("total", orders.getTotal());
			mv.addObject("paid", orders.getPaid());
			mv.addObject("payable",orders.getPayable());
			mv.addObject("tax", orders.getTax());
			
			mv.addObject("orderNumber", orders.getOrdernumber());
			Customer c = customerService.selectByPrimaryKey(orders.getCustomerid());
			mv.addObject("customerId", c.getId());
			mv.addObject("name", c.getName());
			mv.addObject("card", c.getCard());
		}
		return mv;
	}

	/**
	 * 更新订单页
	 */
	@RequestMapping(value = "/updateOrder", method = RequestMethod.POST)
	public ModelAndView updateOrderPost(HttpSession session, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		logger.info("更新订单页");
		Object userId = session.getAttribute(Constants.USER_ID);
		Integer updateuser = Integer.valueOf(userId.toString());

		String customerid = request.getParameter("customerId");
		String address = request.getParameter("address");
		String freightstation = request.getParameter("freightstation");
		// String number = request.getParameter("number");
		String tax = request.getParameter("tax");
		String orderNumber = request.getParameter("orderNumber");
		String paid = request.getParameter("paid");
		// String payable = request.getParameter("payable");
		String paymentstatus = request.getParameter("paymentStatus");
		String remark = request.getParameter("remark");
		// String total = request.getParameter("total");
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("orderNumber", orderNumber);
		Orders o = ordersService.selectByOrderNumber(param);
		// o.setOrdernumber(ordernumber);
		// o.setCustomerid(Integer.valueOf(customerid));
		o.setAddress(address);
		o.setFreightstation(freightstation);
		if (StringUtils.isBlank(tax)) {
			o.setTax(0);
		} else {
			o.setTax(Integer.valueOf(tax));
		}
		// o.setNumber(Integer.valueOf(number));
		o.setPaid(new BigDecimal(paid));
		// o.setPayable(payable);
		o.setPaymentstatus(paymentstatus);
		o.setRemark(remark);
		// o.setTotal(total);
		o.setUpdatetime(new Date());
		o.setUpdateuser(updateuser);
		ordersService.updateByPrimaryKeySelective(o);

		// 同步更新合计
		scyUpdateCustomerTotal(o.getOrdernumber());
		redirectAttributes.addAttribute("customerId", customerid);
		return new ModelAndView("redirect:/security/order");
	}

	/**
	 * 跳转添加订单页
	 */
	@RequestMapping(value = "/addOrder", method = RequestMethod.GET)
	public ModelAndView addOrderGet(HttpSession session, HttpServletRequest request) {
		logger.info("跳转到添加订单页");
		ModelAndView mv = new ModelAndView("order/order_add");
		String customerId = request.getParameter("customerId");
		// String customerId = "28";
		if (StringUtils.isNotBlank(customerId)) {
			Customer c = customerService.selectByPrimaryKey(Integer.valueOf(customerId));
			mv.addObject("customerId", c.getId());
			mv.addObject("name", c.getName());
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("customerId", c.getId());
			param.put("frequently", true);
			Address a = addressService.getFrequentlyDef(param);
			if (a != null) {
				StringBuffer sb = new StringBuffer();
				sb.append(a.getAddress()).append(" ");
				sb.append(a.getDetailedAddress()).append(" ");
				sb.append(a.getName()).append(" ");
				sb.append(a.getTelephone());
				mv.addObject("address", a.getId());
				mv.addObject("addressText", sb.toString());
			}
			String nowdate = new SimpleDateFormat("yyyyMMdd").format(new Date());
			Integer on = ordersService.selectMaxOrderNumber(nowdate);
			String orderNumber = null;
			if (on > 0) {
				StringBuffer sb = new StringBuffer(on.toString());
				String s = sb.substring(sb.length() - 2, sb.length());
				String d = sb.substring(0, sb.length() - 2);
				StringBuffer sb1 = new StringBuffer((Integer.valueOf(s) + 1) + "");
				if (sb1.length() == 2) {
					orderNumber = d + sb1;
				} else {
					sb1.insert(0, "0");
					orderNumber = d + sb1;
				}
			} else {
				orderNumber = nowdate + "01";
			}
			mv.addObject("orderNumber", orderNumber);
		}
		return mv;
	}

	/**
	 * 跳转添加订单页
	 */
	@RequestMapping(value = "/addOrder", method = RequestMethod.POST)
	public ModelAndView addOrderPost(HttpSession session, HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		logger.info("添加订单页");
		Object userId = session.getAttribute(Constants.USER_ID);
		Integer createuser = Integer.valueOf(userId.toString());

		String customerid = request.getParameter("customerId");
		// String address = request.getParameter("addressText");
		String address = request.getParameter("address");
		String freightstation = request.getParameter("freightstation");
		String freightstationcard = request.getParameter("freightstationcard");
		//String number = request.getParameter("number");
		String tax = request.getParameter("tax");
		String ordernumber = request.getParameter("orderNumber");
		String paid = request.getParameter("paid");
		//String payable = request.getParameter("payable");
		String paymentstatus = request.getParameter("paymentStatus");
		String remark = request.getParameter("remark");
		//String total = request.getParameter("total");

		Orders o = new Orders();
		o.setOrdernumber(ordernumber);
		o.setCustomerid(Integer.valueOf(customerid));
		o.setAddress(address);
		o.setFreightstation(freightstation);
		o.setFreightstationcard(freightstationcard);
		// o.setNumber(Integer.valueOf(number));
		if (StringUtils.isNotBlank(paid)) {
			o.setPaid(new BigDecimal(paid));
		}
		if (StringUtils.isBlank(tax)) {
			o.setTax(0);
		} else {
			o.setTax(Integer.valueOf(tax));
		}
		// o.setPayable(payable);
		o.setPaymentstatus(paymentstatus);
		o.setRemark(remark);
		// o.setTotal(total);

		o.setStatus("新单");
		o.setCreateuser(createuser);
		ordersService.insertSelective(o);
		redirectAttributes.addAttribute("customerId", customerid);
		return new ModelAndView("redirect:/security/order");
	}

	/**
	 * 跳转查询订单页
	 */
	@RequestMapping(value = "/order", method = RequestMethod.GET)
	public ModelAndView orderGet(HttpSession session, HttpServletRequest request) {
		logger.info("跳转到订查询单页");
		ModelAndView mv = new ModelAndView("order/order");
		String customerId = request.getParameter("customerId");
		if (StringUtils.isNotBlank(customerId)) {
			Customer c = customerService.selectByPrimaryKey(Integer.valueOf(customerId));
			mv.addObject("customerId", c.getId());
			mv.addObject("name", c.getName());
			// mv.addObject("card", c.getCard());
		}
		return mv;
	}

	@RequestMapping(value = "/order", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> orderPost(HttpSession session, HttpServletRequest request) {

		logger.info("跳转订单查询产品页");
		Map<String, Object> map = new HashMap<String, Object>();
		Integer customerId = null;
		String id = request.getParameter("customerId");
		String name = request.getParameter("name");
		String orderNumber = request.getParameter("orderNumber");
		String createTime = request.getParameter("createTime");
		String status = request.getParameter("status");
		String paymentStatus = request.getParameter("paymentStatus");
		if (StringUtils.isNotBlank(id)) {
			customerId = Integer.valueOf(id);
		}
		int totle = 1;
		List<Orders> list = null;
		// 组合查询参数
		int page = Integer.valueOf(request.getParameter("page"));
		Map<String, Object> param = new HashMap<String, Object>();

		param.put("customerId", customerId);

		if (StringUtils.isNotBlank(name)) {
			param.put("name", name);
		}
		if (StringUtils.isNotBlank(orderNumber)) {
			param.put("orderNumber", orderNumber);
		}
		if (StringUtils.isNotBlank(createTime)) {
			param.put("createTime", createTime);
		}
		if (StringUtils.isNotBlank(status)) {
			param.put("status", status);
		}
		if (StringUtils.isNotBlank(paymentStatus)) {
			param.put("paymentStatus", paymentStatus);
		}
		param.put("page", (page - 1) * 20);
		param.put("totle", 20);
		list = ordersService.selectByParam(param);
		// list = orderService.selectOrderNumbers(param);
		totle = ordersService.selectByParamCount(param);
		int u = totle % 20;
		int pageCount = 1;
		if (u > 0) {
			pageCount = totle / 20 + 1;
		} else {
			pageCount = totle / 20;
		}
		
		for (Iterator<Orders> iterator = list.iterator(); iterator.hasNext();) {
			Orders orders = (Orders) iterator.next();
			logger.info(orders.toString());
			// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm",
			// Locale.getDefault());
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
			sdf.setTimeZone(TimeZone.getTimeZone("GMT+0"));
			String s = sdf.format(orders.getCreatetime());
			orders.setOrderCreateTime(s);
			String address = orders.getAddress();
			if (StringUtils.isNoneBlank(address)) {
				Address a = addressService.selectByPrimaryKey(Integer.valueOf(address));
				StringBuffer sb = new StringBuffer();
				sb.append(a.getAddress()).append(" ");
				sb.append(a.getDetailedAddress()).append(" ");
				// sb.append(a.getName()).append(" ");
				// sb.append(a.getTelephone());
				orders.setAddress(sb.toString());
			}

		}
		map.put(Constants.LIST, list);
		Orders ordersCount = ordersService.selectByCount(param);
		map.put("count", ordersCount);
		map.put(Constants.TOTLE, totle);
		map.put(Constants.TOTLE_PAGE, pageCount);
		return map;
	}

	@RequestMapping(value = "/deleteOrder", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteOrder(HttpSession session, HttpServletRequest request) {
		logger.info("跳转订单查询产品页");
		Map<String, Object> map = new HashMap<String, Object>();
		String id = request.getParameter("id");

		Orders o = ordersService.selectByPrimaryKey(Integer.valueOf(id));
		if (o != null) {
			productService.deleteByOrderId(o.getOrdernumber());
			int d = ordersService.deleteByPrimaryKey(Integer.valueOf(id));
			if (d != 0) {
				map.put("message", "删除成功");
			}
		}

		return map;
	}

}
